<?php


namespace App\Services;


use App\Models\Owner;
use App\Models\OwnerItem;

class OwnerService
{
    public function handle($owner)
    {
        // 判断如果是月
        if ($owner->cycle_unit == Owner::CYCLE_UNIT_YEAR) {
            $this->generateRunningWater($owner, $owner->cycle, 'year');
        } elseif ($owner->cycle_unit == Owner::CYCLE_UNIT_MONTH) { // 判断如果是年
            $this->generateRunningWater($owner, $owner->cycle);
        } else {  // 如果是日
            $this->generateRunningWater($owner, $owner->cycle, 'day');
        }
    }

    private function generateRunningWater($owner, $cycle, $unit = 'month')
    {
        $method = "add" . ucfirst($unit) . "s";
        $count = 1;

        $inc = $owner->inc;

        while ($owner->ended_at->gt($owner->started_at)) {
            $next_time = $owner->started_at->$method($cycle); // 下次交租时间

            // 判断该流水是否已经存在
            if (OwnerItem::query()->where('started_at', $owner->started_at)
                ->where('ended_at', $next_time)
                ->where('owner_id', $owner->id)
                ->where('count', $count)
                ->doesntExist()) {

                $type = OwnerItem::TYPE_DEFAULT;

                if ($next_time->gt($owner->ended_at)) {
                    $type = OwnerItem::TYPE_EXCEED;
                    $exceed_day = (intval($owner->ended_at->timestamp) - intval($owner->started_at->timestamp)) / (60 * 60 * 24);
                    $next_time = $owner->ended_at;
                }
                $rent = big_number($inc)->multiply($count - 1)->add($owner->cycle_price)->getValue();
                $saveData = [
                    'count' => $count,
                    'started_at' => $owner->started_at,
                    'ended_at' => $next_time,
                    'rent' => $rent,
                    'type' => $type,
                    'exceed_day' => $type == OwnerItem::TYPE_DEFAULT ? 0 : ($exceed_day ?? 0)
                ];

                if (!$owner->config) {
                    $saveData['total_amount'] = $rent;
                }

                $owner->items()->create($saveData);
            }
            $count ++;
            $owner->started_at = $next_time;
        }
    }
}